package com.htx.zqs.blesmartmask.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.LinearLayout;

import com.htx.zqs.blesmartmask.BuildConfig;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.custom.MediaScanner;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by zhao on 2018/6/7.
 */

public class CameraUtil {

    private Dialog mCameraDialog;
    private File tempFile;
    private LinearLayout root;

    public Dialog getCameraDialog(Activity context, View.OnClickListener btnlistener, int id, int type) {
        mCameraDialog = new Dialog(context, R.style.my_dialog);
        root = (LinearLayout) LayoutInflater.from(context).inflate(
                id, null);
        root.findViewById(R.id.btn_open_camera).setOnClickListener(btnlistener);
        root.findViewById(R.id.btn_choose_img).setOnClickListener(btnlistener);
        if (type == 0) {
            root.findViewById(R.id.btn_start_Course).setOnClickListener(btnlistener);

        } else {
            root.findViewById(R.id.btn_start_Course).setVisibility(View.GONE);
        }
        mCameraDialog.setContentView(root);
        Window dialogWindow = mCameraDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.dialogstyle); // 添加动画
        WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        lp.x = 0; // 新位置X坐标
        lp.y = -20; // 新位置Y坐标
        lp.width = (int) context.getResources().getDisplayMetrics().widthPixels; // 宽度
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度
        lp.alpha = 9f; // 透明度
        root.measure(0, 0);
//        lp.height = root.getMeasuredHeight();
//        lp.alpha = 9f; // 透明度
        dialogWindow.setAttributes(lp);
        mCameraDialog.show();
        return mCameraDialog;
    }


    /**
     * 使用系统相机进行拍照
     */
    public File useCamera(Activity activity, int type) {
        //用于保存调用相机拍照后所生成的文件
        File s = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/"+activity.getResources().getString(R.string.app_name));
        if(!s.exists()){
            s.mkdirs();
        }
        tempFile = new File(s, System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // intent.putExtra("camerasensortype", 2); // 调用前置摄像头
        if (type == 1) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 调用前置摄像头
        }
//        intent.putExtra("autofocus", true); // 自动对焦
//        intent.putExtra("fullScreen", false); // 全屏
//        intent.putExtra("showActionIcons", false);
        //判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(activity,BuildConfig.APPLICATION_ID+".fileprovider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            Log.e("dasd", contentUri.toString());
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        activity.startActivityForResult(intent, Contants.CAMERA_REQUEST_CODE);
        return tempFile;
    }

    /**
     * 使用系统相机进行拍照
     */
    public File useFragmentCamera(android.support.v4.app.Fragment activity, int type) {

        //用于保存调用相机拍照后所生成的文件
//        tempFile = new File(Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/", System.currentTimeMillis() + ".jpg");
        File s = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/"+activity.getResources().getString(R.string.app_name));
        if(!s.exists()){
           s.mkdirs();
        }

        tempFile = new File(s, System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // intent.putExtra("camerasensortype", 2); // 调用前置摄像头
        if (type == 1) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", 1); // 调用前置摄像头
        }
//        intent.putExtra("autofocus", true); // 自动对焦
//        intent.putExtra("fullScreen", false); // 全屏
//        intent.putExtra("showActionIcons", false);
        //判断版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   //如果在Android7.0以上,使用FileProvider获取Uri
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(activity.getActivity(), BuildConfig.APPLICATION_ID+".fileprovider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            Log.e("dasd", contentUri.toString());
        } else {    //否则使用Uri.fromFile(file)方法获取Uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        activity.startActivityForResult(intent, Contants.CAMERA_REQUEST_CODE);
        return tempFile;
    }

    /**
     * 刷新图片到相册
     * @param context
     * @param path
     */
    public static void flushPciture(Context context, String path){

        MediaScanner mediaScanner = new MediaScanner(context);
        String[] filePaths = new String[]{path};
        Log.e("==170==","==="+filePaths);
        String[] mimeTypes = new String[]{MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg")};
        mediaScanner.scanFiles(filePaths, mimeTypes);
    }

    public void usePicture(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        activity.startActivityForResult(intent, Contants.IMAGE_REQUEST_CODE);
    }

    public void useFragmentPicture(android.support.v4.app.Fragment fragment) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        fragment.startActivityForResult(intent, Contants.IMAGE_REQUEST_CODE);
    }


    public static Bitmap returnBitMap(final String url){
        URL imageurl = null;
        Bitmap bitmap = null;
        try {
            imageurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
             bitmap = BitmapFactory.decodeStream(is);
            is.close();
            Log.e("xk","bitmapIO = " + bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("xk","bitmapRuntrn = " + bitmap);
        return bitmap;
    }


    //**
//        * 通过uri获取图片并进行压缩
//     *
//             * @param uri
//     */
    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    public static void saveImage(Bitmap bitmap) {
        File appDir = new File(Environment.getExternalStorageDirectory().getPath());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "aaa.jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
